package com.mingqijia.gassafety.webserver.service.impl;

import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.dto.TaskTemplateListParamDTO;
import com.mingqijia.gassafety.shared.dto.TaskTemplateListRespDTO;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.message.SendMessageService;
import com.mingqijia.gassafety.webserver.request.TemplateListRequest;
import com.mingqijia.gassafety.webserver.service.CompanyService;
import com.mingqijia.gassafety.webserver.service.MessageService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @author: duanhongxiang
 * @Desc:
 * @create: 2024-10-18 15:16
 **/
@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    SendMessageService sendMessageService;

    @Resource
    CompanyService companyService;

    @Override
    public List<TaskTemplateListRespDTO> getTemplateListByCode(TemplateListRequest request) {
        if (StringUtils.isEmpty(request.getCode()) && StringUtils.isEmpty(request.getCodePrefix()) && StringUtils.isEmpty(request.getStrategyType())) {
            throw new BizException("code,codePrefix,strategyType参数必须有一个有值！");
        }
        String spId = ApplicationUtils.getWorkingSpId();
        String orgCode = "";
        if (StringUtils.isEmpty(request.getOrgCode())) {
            List<String> orgCodes = companyService.getOrgCodeBySubsCode(spId);
            if (null!=orgCodes && !orgCodes.isEmpty()) {
                orgCode = orgCodes.size() > 1 ? orgCodes.get(1) : orgCodes.get(0);
            }
        }else{
            orgCode = request.getOrgCode();
        }
        if (StringUtils.isEmpty(orgCode)){
            orgCode = companyService.getOrgCode(spId, null);
        }
        TaskTemplateListParamDTO paramDTO = new TaskTemplateListParamDTO();
        if ( !StringUtils.isEmpty(request.getStrategyType()) ){
            String codePrefix = Constants.MSG_TYPE_STRAGEY_TYPE_WXTPL_MSG_CODE_MAP.
                    getOrDefault(request.getMsgType(), Collections.emptyMap()).
                    get(request.getStrategyType());
            if (StringUtils.isEmpty(codePrefix)){
                throw new BizException("未找到strategyType匹配的策略类型！");
            }
            paramDTO.setCodePrefix(codePrefix);
        }else if ( !StringUtils.isEmpty(request.getCode()) ){
            paramDTO.setCode(request.getCode());
        }else if( !StringUtils.isEmpty(request.getCodePrefix()) ){
            paramDTO.setCodePrefix(request.getCodePrefix());
        }
        paramDTO.setMsgType(request.getMsgType());
        paramDTO.setOrgCode(orgCode);
        paramDTO.setSpId(spId);
        List<TaskTemplateListRespDTO> resp =  sendMessageService.getMsgTemplateList(paramDTO);
        return resp;
    }
}
